package com.hxkcloud.nurse.activitys;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hxkcloud.nurse.R;
import com.hxkcloud.nurse.adapter.PerformListAdapter;
import com.hxkcloud.nurse.beans.DepartmentOrderBean;
import com.hxkcloud.nurse.popup.CalendarPopWindow;
import com.hxkcloud.nurse.request.MessageCode;
import com.hxkcloud.nurse.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.nurse.utils.BrightnessUtils;
import com.hxkcloud.nurse.views.ListDividerItemDecoration;
import com.hxkcloud.nurse.views.pulltorefreshlayout.PullToRefreshLayout;
import com.hxkcloud.nurse.views.pulltorefreshlayout.PullableRecyclerView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 科室执行单列表
 * Created by ray_lei on 2016/7/13.
 */
public class PerformListActivity extends BaseActivity implements View.OnClickListener, PerformListAdapter.ResultSelectedListener, PullToRefreshLayout.OnRefreshListener {

    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private TextView tv_new;

    private PullToRefreshLayout refreshLayout;
    private PullableRecyclerView recycleView;

    private TextView tv_notice;

    private List<DepartmentOrderBean> stringInfoList;
    private PerformListAdapter adapter;

    private PopupWindow popup;
    private Button previewBtn;
    private Button deleteBtn;
    private Button nowBtn;
    private Button timerBtn;
    private Button cancelBtn;

    //两个按钮
    private PopupWindow popup_easynotice;
    private TextView tv_easynotice_title;
    private TextView tv_easynotice_cancel;
    private TextView tv_easynotice_func;

    private CalendarPopWindow calendarView;
    private DepartmentOrderBean functionOrder;//popup展示时的order

    private int type = 0;//0执行单 1提醒单
    private String patientId = "";
    private boolean useFinish = false;//是否使用后关闭此页面

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_DOORDERLIST_SUCCESS:
                refreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                stringInfoList = (List<DepartmentOrderBean>) msg.obj;
                adapter.setData(stringInfoList);
                break;
            case MessageCode.NETWORKCODE_DOORDERLIST_FAILURE:
                refreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.datagetfail);
                }
                break;
            case MessageCode.NETWORKCODE_DOORDERDELETE_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.datadeletefail);
                }
                break;
            case MessageCode.NETWORKCODE_DOORDERDELETE_SUCCESS:
                loading();
                YiJiaHuNetWorkUtils.doOrderList(type, loginInfo.getDepartmentId(), handler);
                break;
            case MessageCode.NETWORKCODE_DOORDERUSE_SUCCESS:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.datacommitsuccess);
                }
                if (useFinish) {
                    finish();
                }
                break;
            case MessageCode.NETWORKCODE_DOORDERUSE_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.datacommitfail);
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_performlist);
        stringInfoList = new ArrayList<DepartmentOrderBean>();

        type = this.getIntent().getIntExtra("type", 0);
        patientId = this.getIntent().getStringExtra("patientId");
        useFinish = getIntent().getBooleanExtra("usefinish", false);

        initView();
        initData();
        initListener();
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        tv_new = (TextView) findViewById(R.id.tv_title_func);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        if (type == 0) {
            tv_title.setText(getResources().getText(R.string.departmentperformlist));
        } else {
            tv_title.setText(getResources().getText(R.string.departmentremindlist));
        }

        tv_new.setVisibility(View.VISIBLE);
        tv_new.setText(getResources().getText(R.string.performlist_text_create));
        iv_back.setOnClickListener(this);
        tv_new.setOnClickListener(this);

        tv_notice = (TextView) findViewById(R.id.performlist_notice);
        refreshLayout = (PullToRefreshLayout) findViewById(R.id.performlist_refreshlayout);
        recycleView = (PullableRecyclerView) findViewById(R.id.performlist_recyclerview);
        if (type == 0) {
            tv_notice.setText(getResources().getText(R.string.performlist_text_tip));
        } else {
            tv_notice.setText(getResources().getText(R.string.remindlist_text_tip));
        }

//        recycleView.setCanLoadMore(false);
        recycleView.setCanRefresh(true);
        recycleView.setCanLoadMore(false);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(mLayoutManager);
        ListDividerItemDecoration itemDecoration = new ListDividerItemDecoration(
                this, ListDividerItemDecoration.VERTICAL_LIST);
        recycleView.addItemDecoration(itemDecoration);
        refreshLayout.setOnRefreshListener(this);

        adapter = new PerformListAdapter(this, stringInfoList, recycleView, this);
        recycleView.setAdapter(adapter);

        initPopup();

    }

    private void initPopup() {
        popup = new PopupWindow(this);
        View viewSex = LayoutInflater.from(this).inflate(R.layout.popup_perform_select, null);
        popup.setContentView(viewSex);

        popup.setWidth(screenWidth);
        popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup.setFocusable(true);
        popup.setTouchable(true);
        popup.setOutsideTouchable(true);
        popup.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup.setAnimationStyle(R.style.popupwindow_anim_default);

        previewBtn = (Button) viewSex.findViewById(R.id.bt_select_preview);
        deleteBtn = (Button) viewSex.findViewById(R.id.bt_select_delete);
        nowBtn = (Button) viewSex.findViewById(R.id.bt_select_now);
        timerBtn = (Button) viewSex.findViewById(R.id.bt_select_timer);
        cancelBtn = (Button) viewSex.findViewById(R.id.bt_select_cancel);

        previewBtn.setOnClickListener(this);
        deleteBtn.setOnClickListener(this);
        nowBtn.setOnClickListener(this);
        timerBtn.setOnClickListener(this);
        cancelBtn.setOnClickListener(this);

        popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(PerformListActivity.this);
            }
        });


        popup_easynotice = new PopupWindow(this);
        View viewNotice = LayoutInflater.from(this).inflate(R.layout.popup_easynotice, null);
        popup_easynotice.setContentView(viewNotice);

        popup_easynotice.setWidth((int) (screenWidth * 0.7));
        popup_easynotice.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_easynotice.setFocusable(true);
        popup_easynotice.setTouchable(true);
        popup_easynotice.setOutsideTouchable(true);
        popup_easynotice.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_easynotice.setAnimationStyle(R.style.popupwindow_anim_alpha);

        tv_easynotice_title = (TextView) viewNotice.findViewById(R.id.tv_easynotice_title);
        tv_easynotice_cancel = (TextView) viewNotice.findViewById(R.id.tv_easynotice_cancel);
        tv_easynotice_func = (TextView) viewNotice.findViewById(R.id.tv_easynotice_func);

        tv_easynotice_cancel.setOnClickListener(this);
        tv_easynotice_func.setOnClickListener(this);

        popup_easynotice.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(PerformListActivity.this);
            }
        });
    }

    @Override
    protected void initListener() {
        iv_back.setOnClickListener(this);
        tv_new.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        loading();
        YiJiaHuNetWorkUtils.doOrderList(type, loginInfo.getDepartmentId(), handler);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back://back
                finish();
                break;
            case R.id.tv_title_func://新建
                Intent iDolist = new Intent(mContext, NewDolistActivity.class);
                iDolist.putExtra("type", type);
                iDolist.putExtra("patientId", patientId);
//                ParcelableBean bean = new ParcelableBean();
//                bean.setId("1");
//                bean.setName("st");
//                iDolist.putExtra("p", bean);
                startActivity(iDolist);
                if (!TextUtils.isEmpty(patientId)) {
                    finish();
                }
                break;
            case R.id.bt_select_preview://预览
                popup.dismiss();
                if (functionOrder != null) {
                    Intent iPreview = new Intent(mContext, DolistPreviewActivity.class);
                    iPreview.putExtra("title", functionOrder.getOrderName());
                    iPreview.putExtra("id", functionOrder.getOrderId());
                    iPreview.putExtra("type", type);
                    iPreview.putExtra("patientId", patientId);
                    startActivityForResult(iPreview, 125);
                }
                break;
            case R.id.bt_select_delete://删除
                popup.dismiss();

                tv_easynotice_title.setText(getResources().getString(R.string.remind_sure_delete));
                tv_easynotice_func.setText(getResources().getString(R.string.remind_sure));
                tv_easynotice_cancel.setText(getResources().getString(R.string.remind_cancel));
                popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
                BrightnessUtils.lightOff(this);

                break;
            case R.id.bt_select_now://立即使用
                popup.dismiss();
                if (functionOrder != null) {
                    if (!TextUtils.isEmpty(patientId)) {
                        List<String> patients = new ArrayList<>();
                        patients.add(patientId);
                        Calendar cal = Calendar.getInstance();
                        String date = "" + cal.getTime().getTime();
                        loading();
                        YiJiaHuNetWorkUtils.doOrderUse(patients, date, functionOrder.getOrderId(), handler);
                    } else {
                        Intent iPatient = new Intent(mContext, ChooseUserActivity.class);
                        startActivityForResult(iPatient, 123);
                    }
                }
                break;
            case R.id.bt_select_timer://定时使用
                popup.dismiss();
                if (functionOrder != null) {
                    if (calendarView == null) {
                        calendarView = new CalendarPopWindow(this);
                    }
                    calendarView.setCalendarListener(new CalendarPopWindow.CalendarListener() {
                        @Override
                        public void setCalendar(String calendar) {
                            List<String> patients = new ArrayList<>();
                            patients.add(patientId);
                            chooseDate = 0;
                            long cur = 0;
                            try {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                chooseDate = sdf.parse(calendar).getTime();
                                Calendar cal = Calendar.getInstance();
                                cur = cal.getTime().getTime();
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            if (chooseDate < cur) {
                                toastMsg(R.string.pleasechoosecorrecttime);
                            } else {
                                if (!TextUtils.isEmpty(patientId)) {
                                    loading();
                                    YiJiaHuNetWorkUtils.doOrderUse(patients, "" + chooseDate, functionOrder.getOrderId(), handler);
                                } else {
                                    Intent iPatient = new Intent(mContext, ChooseUserActivity.class);
                                    startActivityForResult(iPatient, 124);
                                }
                            }
                        }
                    });
                    calendarView.showBottom(ll_title);
                }
                break;
            case R.id.bt_select_cancel://取消
                popup.dismiss();
                break;
            case R.id.tv_easynotice_cancel:
                popup_easynotice.dismiss();
                break;
            case R.id.tv_easynotice_func:
                popup_easynotice.dismiss();

                if (functionOrder != null) {
                    if (functionOrder.getType().equals("1")) {
                        loading();
                        YiJiaHuNetWorkUtils.doOrderDelete(functionOrder.getOrderId(), handler);
                    } else {
                        toastMsg(R.string.cantmodifyothers);
                    }
                }
                break;
        }
    }

    @Override
    public void onSelected(String type, DepartmentOrderBean info) {
        if ("click".equals(type)) {
//            closeInputMethodManager();
            functionOrder = info;
            popup.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
            BrightnessUtils.lightOff(PerformListActivity.this);
        }
    }

    private long chooseDate = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 123) {
                List<String> patients = data.getStringArrayListExtra("patients");
                Calendar cal = Calendar.getInstance();
                String date = "" + cal.getTime().getTime();
                loading();
                YiJiaHuNetWorkUtils.doOrderUse(patients, date, functionOrder.getOrderId(), handler);
            } else if (requestCode == 124) {
                ArrayList<String> patients = data.getStringArrayListExtra("patients");
                patients.addAll(patients);
                loading();
                YiJiaHuNetWorkUtils.doOrderUse(patients, chooseDate + "", functionOrder.getOrderId(), handler);
            } else if (requestCode == 125) {
                if (data.getBooleanExtra("use", false)) {
                    if (useFinish) {
                        finish();
                    }
                }
            }
        }
    }

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        loading();
        YiJiaHuNetWorkUtils.doOrderList(type, loginInfo.getDepartmentId(), handler);
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }
}
